import React from 'react';
import { connect } from 'dva';
import { Table, message } from 'antd';
import _ from 'lodash';
import { Link } from 'dva/router';
import { getCol } from '../task/col';
import RecordList from './record';
import PackModal from './packModal';
import { toBase64 } from '../../utils';

const styles = require('../app.less');

// 这个界面主要用于处理package之间的关系的
class Record extends React.Component {
  constructor(p) {
    super(p);
    this.queryData = this.queryData.bind(this);
    this.handlePackModalFinish = this.handlePackModalFinish.bind(this); // 打包Modal的打开
    this.getPackOp = this.getPackOp.bind(this); // 打包表的操作选项

    this.state = {
      packModalVisible: false,
      editPack: null,
    };
  }

  componentDidMount() {
    this.queryData();
  }

  getPackOp() {
    const showPackModal = (item) => {
      return () => {
        this.setState({
          editPack: item,
          packModalVisible: true,
        });
      };
    };

    return [{
      title: '操作',
      key: 'op',
      render: (text, record) => {
        return (
          <div>
            {/* <a onClick={showPackModal(record)}>编辑</a> */}
            {/* | */}
            <Link to={`/packDetail?packId=${record.id}&data=${toBase64(record)}`}>查看</Link>
            |
            <a onClick={() => message.error('尚未开放')}>删除</a>
          </div>
        );
      },
    }];
  }

  queryData() {
    const id = _.get(this, 'props.location.query.taskId');
    const { dispatch } = this.props;
    // 查询包
    dispatch({
      type: 'record/queryPackage',
      payload: {
        id,
      },
    });
  }

  handlePackModalFinish() {
    this.setState({
      packModalVisible: false,
      editPack: null,
    });
    this.queryData();
  }

  render() {
    const {
      packages, packageKeys,
    } = this.props.record;

    const { loading } = this.props;
    const { packModalVisible, editPack } = this.state;
    const id = _.get(this, 'props.location.query.taskId');
    return (
      <div className={styles.container}>
        {
          packModalVisible &&
            <PackModal
              visible={packModalVisible}
              onFinish={this.handlePackModalFinish}
              data={editPack}
              loading={loading}
            />
        }
        <h2>任务详情</h2>
        <h3>包列表:</h3>
        <Table
          columns={_.unionBy(getCol(packageKeys), this.getPackOp(), 'key')}
          dataSource={packages}
          loading={loading.effects['record/queryPackage']}
          rowKey="id"
        />
        <RecordList
          fatherId={id}
          loading={loading}
          hasRecord={false}
        />
      </div>
    );
  }
}

export default connect(state => state)(Record);
